package net.sudot.chess.listener.game;

import net.sudot.chess.business.model.Room;
import net.sudot.chess.business.model.WechatGroup;
import net.sudot.chess.business.service.RoomService;
import net.sudot.chess.business.service.WechatBotService;
import net.sudot.chess.business.service.WechatGroupService;
import net.sudot.chess.event.game.StartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 游戏开始事件
 *
 * @author tangjialin on 2018-06-19.
 */
@Component
public class StartedEventListener implements ApplicationListener<StartedEvent> {

    @Resource
    private RoomService roomService;
    @Resource
    private WechatGroupService wechatGroupService;
    @Resource
    private WechatBotService wechatBotService;

    @Override
    public void onApplicationEvent(StartedEvent event) {
        Room room = event.getRoom();
        Long gameId = room.getGameId();
        // 根据gameId查询房间名称
        WechatGroup wechatGroup = wechatGroupService.findUnUseByGame(gameId);
        if (wechatGroup == null) { return; }
        String wechatGroupName = wechatGroup.getName();
        if (wechatGroupName == null) { return; }
        room.setWechatGroupId(wechatGroup.getId()).setWechatGroupName(wechatGroupName);
        roomService.update(room);
        wechatGroupService.update(wechatGroup.setUsed(true));

        wechatBotService.sendOpenRoomCommand(wechatGroupName);
    }

}
